package com.tg.appcommon.android;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.StringRes;
import com.appbase.custom.R;
import com.tange.base.toolkit.AppUtil;
import com.tange.base.toolkit.DimenUtil;
import com.tange.base.toolkit.TGThreadPool;

/**
 * 应用中统一弹Toast的接口
 * <p>
 * 注意：2s内相同内容的toast会被过滤掉
 */
public class TGToast {

    public static void showToast(Context context, @StringRes int messageId) {
        showToast(context, getString(context, messageId));
    }

    public static void showToast(Context context, String message) {
        showToast(context, message, 0, Toast.LENGTH_SHORT);
    }

    public static void showToast(Context context, String message, int maxLines) {
        showToast(context, message, maxLines, Toast.LENGTH_SHORT);
    }

    public static void showToast(final Context context, final String message, final int maxLines, final int duration) {
        if (context instanceof Activity && AppUtil.isActivityFinishingOrDestroyed(context)) {
            return;
        }
        try {
            Impl.showToastImpl(context, message, maxLines, Gravity.BOTTOM, duration);
        } catch (Exception e) {

        }
    }

    public static void showToastWithDuration(Context context, String message, int duration) {
        showToast(context, message, 0, duration);
    }

    public static void showLongToast(Context context, String message) {
        TGThreadPool.executeOnUiThread(() -> showToast(context, message, 0, Toast.LENGTH_LONG));

    }

    /**
     * 显示 "无网络连接" 的Toast
     */
    public static void showNoNetworkToast(Context context) {
        if (sNetworkToastManager.isNoNetworkToastForbidden()) {
            // 暂时屏蔽了"无网络连接" 的Toast
            return;
        }
        showToast(context, getString(context, R.string.commonui_no_network_toast));
    }

    public static void cancelAllToast() {
        Impl.cancelAllToast();
    }

    /**
     * 设置是否禁止弹"无网络连接" 的Toast
     */
    public static void setNoNetworkToastForbidden(boolean isForbidden) {
        sNetworkToastManager.setNoNetworkToastForbidden(isForbidden);
    }

    private static String getString(Context context, @StringRes int messageId) {
        Resources resources;
        if (context instanceof Activity) {
            resources = context.getResources();
        } else {
            resources = TGApplicationBase.getApplicationContext().getResources();
        }
        return resources.getString(messageId);
    }

    private static class NetworkToastManager {

        void setNoNetworkToastForbidden(boolean isForbidden) {
            mIsNoNetworkToastForbidden = isForbidden;
            mLastTimeForNoNetworkToastForbidden = System.currentTimeMillis();
        }

        boolean mIsNoNetworkToastForbidden = false;
        long mLastTimeForNoNetworkToastForbidden = 0;

        boolean isNoNetworkToastForbidden() {
            if (mIsNoNetworkToastForbidden) {
                long time = System.currentTimeMillis() - mLastTimeForNoNetworkToastForbidden;
                if (time > 10000) {
                    // 超过10s开关打开
                    return false;
                }
                return true;
            }
            return false;
        }
    }

    private static final NetworkToastManager sNetworkToastManager = new NetworkToastManager();

    private static class Impl {
        private static final long DROP_DUPLICATE_TOAST_TS = 2 * 1000L; // 2s

        private static String sLastText = "";

        private static long sLastTs = 0;

        private static Toast sBasicToast = null;

        static void showToastImpl(Context context, String message, int maxLines, int gravity, int duration) {
            if (context == null)
                return;
            long newTs = System.currentTimeMillis();
            if (message != null && (!message.equals(sLastText) || newTs < sLastTs || (newTs - sLastTs) > DROP_DUPLICATE_TOAST_TS)) {
                sLastText = message;
                sLastTs = newTs;
                if (sBasicToast == null) {
                    sBasicToast = new Toast(context.getApplicationContext());
                    WindowBadTokenExceptionFixUtil.addToastWindowBadTokenExceptionCatch(sBasicToast);
                }
                View toastView = LayoutInflater.from(context.getApplicationContext()).inflate(com.module.appcommon.R.layout.commonui_toast_view, null);
                TextView textView = toastView.findViewById(com.module.appcommon.R.id.xlui_toast_text);
                textView.setText(message);
                if (maxLines > 0) {
                    textView.setMaxLines(maxLines);
                }
                sBasicToast.setView(toastView);

                int yOffset = 0;

                if (gravity == Gravity.CENTER) {
                    //为了使toast基于全屏居中
                    //需要考虑状态栏和导航栏的高度
                    yOffset = AppUtil.getStatusBarHeight(context.getApplicationContext());
                } else if (gravity == Gravity.BOTTOM) {
                    yOffset = -2 * DimenUtil.dp2px(context.getApplicationContext(), 65);
                }

                sBasicToast.setGravity(gravity, 0, -yOffset / 2);
                sBasicToast.setDuration(duration);// 默认只显示2S
                sBasicToast.show();
            }
        }

        static void cancelAllToast() {
            if (sBasicToast != null) {
                sBasicToast.cancel();
            }
        }
    }

    public static void showToast(final String msg){
        TGThreadPool.executeOnUiThread(() -> Toast.makeText(TGApplicationBase.getApplicationContext(), msg, Toast.LENGTH_SHORT).show());
    }
    public static void showToast(final int resId){
        TGThreadPool.executeOnUiThread(() -> Toast.makeText(TGApplicationBase.getApplicationContext(), ResourcesUtil.getString(resId), Toast.LENGTH_SHORT).show());
    }

}
